import os
import sys
import toml
from pathlib import Path
from typing import Dict, List, Optional
from .driver import Compiler

class BuildSystem:
    def __init__(self, project_dir: str):
        self.project_dir = Path(project_dir)
        self.config_file = self.project_dir / "ink.toml"
        self.config = None
        
    def load_config(self):
        """加载项目配置从 ink.toml"""
        if not self.config_file.exists():
            raise FileNotFoundError(f"项目配置未找到: {self.config_file}")
        
        with open(self.config_file, 'r', encoding='utf-8') as f:
            self.config = toml.load(f)
            
        # 验证必需字段
        if 'project' not in self.config:
            raise ValueError("项目配置中缺少 [project] 部分")
        if 'name' not in self.config['project']:
            raise ValueError("项目配置中 [project] 部分缺少 'name' 字段")
            
    def build(self, clean: bool = False):
        """构建项目"""
        if not self.config:
            self.load_config()
            
        project_name = self.config['project']['name']
        project_type = self.config['project'].get('type', 'executable')
        
        # 获取构建配置
        build_config = self.config.get('build', {})
        main_file = build_config.get('main_file', 'main.ink')
        output_dir = self.project_dir / build_config.get('output_dir', 'target')
        optimization = build_config.get('optimization', 'O2')
        
        # 创建输出目录
        output_dir.mkdir(parents=True, exist_ok=True)
        
        # 如果请求清理
        if clean:
            print(f"清理构建目录: {output_dir}")
            for file in output_dir.glob('*'):
                if file.is_file():
                    file.unlink()
        
        # 编译主文件
        main_path = self.project_dir / main_file
        if not main_path.exists():
            raise FileNotFoundError(f"主文件未找到: {main_path}")
            
        print(f"构建 {project_name} ({project_type})...")
        
        # 确定输出名称
        if project_type == 'executable':
            output_name = output_dir / f"{project_name}.exe"
        else:
            output_name = output_dir / f"{project_name}.lib"
            
        # 编译
        compiler = Compiler()
        compiler.compile_file(str(main_path), str(output_name))
        
        print(f"构建成功！输出: {output_name}")
        return output_name
        
    def run(self):
        """构建并运行项目（如果项目是可执行的）"""
        if not self.config:
            self.load_config()
            
        project_type = self.config['project'].get('type', 'executable')
        if project_type != 'executable':
            raise ValueError("不能运行非可执行项目")
            
        # 先构建
        output_path = self.build()
        
        # 运行
        print(f"\n运行 {output_path}...")
        print("=" * 50)
        import subprocess
        result = subprocess.run([str(output_path)], capture_output=False)
        print("=" * 50)
        print(f"进程退出，返回码: {result.returncode}")
        return result.returncode
        
    def clean(self):
        """清理构建产物"""
        if not self.config:
            self.load_config()
            
        build_config = self.config.get('build', {})
        output_dir = self.project_dir / build_config.get('output_dir', 'target')
        
        if output_dir.exists():
            print(f"清理 {output_dir}...")
            import shutil
            shutil.rmtree(output_dir)
            print("清理完成！")
        else:
            print("没有需要清理的文件。")

def main():
    """构建系统 CLI"""
    if len(sys.argv) < 2:
        print("用法: python -m ink.build <命令> [项目目录]")
        print("命令:")
        print("  build     - 构建项目")
        print("  run       - 构建并运行项目")
        print("  clean     - 清理构建产物")
        print("  rebuild   - 清理并重新构建")
        sys.exit(1)
        
    command = sys.argv[1]
    project_dir = sys.argv[2] if len(sys.argv) > 2 else "."
    
    build_system = BuildSystem(project_dir)
    
    try:
        if command == "build":
            build_system.build()
        elif command == "run":
            build_system.run()
        elif command == "clean":
            build_system.clean()
        elif command == "rebuild":
            build_system.build(clean=True)
        else:
            print(f"Unknown command: {command}")
            sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
